package rs

import (
	"database/sql/driver"
	"strconv"
)

// Value implements sql/driver.Valuer interface.
func (rs Rs) Value() (driver.Value, error) {
	return int64(rs.Intval()), nil
}

// Scan implements sql.Scanner interface.
func (rs *Rs) Scan(value interface{}) error {
	switch value := value.(type) {
	case []byte:
		n, err := strconv.ParseInt(string(value), 10, 32)
		if err != nil {
			return Error.New("parse %T error", value)
		}
		*rs, err = FromInt(uint32(n))
		if err != nil {
			return Error.Wrap(err)
		}
		return nil
	case int64:
		var err error
		*rs, err = FromInt(uint32(value))
		if err != nil {
			return Error.Wrap(err)
		}
		return nil
	default:
		return Error.New("unable to scan %T into rs_coder", value)
	}
}

// NullUUID represents a UUID that may be null.
// NullUUID implements the Scanner interface so it can be used
// as a scan destination, similar to sql.NullString.
type NullRs struct {
	Rs    Rs
	Valid bool // Valid is true if UUID is not NULL
}

// Value implements sql/driver.Valuer interface.
func (n NullRs) Value() (driver.Value, error) {
	if !n.Valid {
		return nil, nil
	}
	return n.Rs.Value()
}

// Scan implements sql.Scanner interface.
func (n *NullRs) Scan(value interface{}) error {
	if value == nil {
		n.Rs, n.Valid = Rs{}, false
		return nil
	}

	n.Valid = true
	return n.Rs.Scan(value)
}
